<?php
namespace app\api\controller;
use think\facade\Db;
use think\facade\Request;

class ApiBase {
	protected $middleware = ["app\api\middleware\Auth"];

	protected $APPID;
	protected $SECRET;
	protected $token;
	protected $uid;
	protected $userInfo;

	public function __construct() {
		$miniApp = Db::name("system")->where("config", "miniapp")->find();
		$this->APPID = $miniApp["value"];
        $this->SECRET = $miniApp["extend"];
        $this->token = Request::header("token");
        $token = $this->token;

        $tks = explode('.', $token);
        if (count($tks) == 3) {
            $checkToken = checkToken($token);
            if($checkToken['code'] == 200){
                $userInfo = checkToken($token)["result"];
                $this->uid = $userInfo->uid;
                $this->userInfo = $userInfo;
            }
		}
	}
	public function sendMsg($from_uid, $to_uid, $post_id, $type, $content="",$title="") {

		/**
		 * type 1为点赞，2为评论  3为收藏 4为关注  5为推送文章 6私聊
		 */
		$data["from_uid"] = $from_uid;
		$data["to_uid"] = $to_uid;
		$data["post_id"] = $post_id;
		$data["title"] = $title;
		$data["content"] = $content;
		$data["type"] = $type;
		$data["create_time"] = time();

		$where["from_uid"] = $from_uid;
		$where["to_uid"] = $to_uid;
		$where["type"] = $type;
		$where["post_id"] = $post_id;
		$where["content"] = $content;

		if ($from_uid != $to_uid) {
			$res = Db::name("message")->where($where)->find();
			if (!$res) {
                Db::name("message")->insert($data);
			}
		}
	}
	public function getAccessToken() {
		$URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" .$this->APPID ."&secret=" .$this->SECRET;
		$res = httpRequest($URL);
		return $res["access_token"];
	}

	public function checkText($content) {
		$Url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $this->getAccessToken();
		$res = httpRequest($Url, json_encode(["content" => $content], JSON_UNESCAPED_UNICODE), "POST");
		return $res["errcode"];
	}

	public function imgCheck($img) {
		$img = file_get_contents($img);
		$filePath = 'uploads/tmp1.png';
		file_put_contents($filePath, $img);
		$obj = new \CURLFile(realpath($filePath));
		$obj->setMimeType("image/jpeg");
		$file['media'] = $obj;
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=$token";
		$info = httpRequest($url, $file, 'POST');
		return $info["errcode"];
	}
}
